articles

Home / DeveloperSection / Articles / Editable Grid View System using BootStrap in ASP.Net

Editable Grid View System using BootStrap in ASP.Net

Editable Grid View System using BootStrap in ASP.Net

Anonymous User 181279 25-Jan-2014

Editable Grid View System using BootStrap in ASP.Net

In this blog, I’m explaining how to make a gridview editable using bootstrap in asp.net.

Step 1:                              

First, create an asp.net empty web application and add a web form to the solution.

Editable Grid View System using BootStrap in ASP.Net

Step 2:

Now add a gridview by drag and drop from the toolbox and give these properties and event:


OnRowCommand="GridView1_RowCommand"
AutoGenerateColumns=”false
AllowPaging=” true
DataKeysName=” ID

 As you make true to these properties, your gridview will look like this:

Step 3:

Now add the below code in the .aspx.cs file: 

protectedvoid Page_Load(object sender, EventArgs e)
{
        DataLoad();
}  
publicvoid DataLoad()
{
   string message = string.Empty;
   try
   {  
      SqlConnection connection = GlobalClass.OpenConnection(out message);
      if (connection != null && string.IsNullOrEmpty(message))
      {
          string cmd = "select * from GridView";
          SqlDataAdapter dAdapter = newSqlDataAdapter(cmd, connection);
          DataSet ds = newDataSet();
          dAdapter.Fill(ds);
          dt = ds.Tables[0];
    //Bind the fetched data to gridview
          grdvCrudOperation.DataSource = dt;
          grdvCrudOperation.DataBind();
          grdvCrudOperation.Columns[3].Visible = false;
       }
   }
   catch (Exception ex)
   {         message = ex.Message;
   }
   finally
   {
        GlobalClass.CloseConnection(out message);
   }
}

 When you run the above code, this will display all values from the Employee table.

Step 4:

To make the gridview editable, create three-button field inside gridview 

1.
<asp:ButtonFieldCommandName="detail" ControlStyle-CssClass="btn btn-info"    ButtonType="Button"Text="Detail"HeaderText="Detailed View">
<ControlStyleCssClass="btn btn-info"></ControlStyle>
</asp:ButtonField>
  2. 
<asp:ButtonFieldCommandName="editRecord" ControlStyle-CssClass="btn btn-info"ButtonType="Button"Text="Edit"HeaderText="Edit Record">
<ControlStyleCssClass="btn btn-info"></ControlStyle>
</asp:ButtonField>
3. 
<asp:ButtonFieldCommandName="deleteRecord" ControlStyle-CssClass="btn btn-info"ButtonType="Button"Text="Delete"HeaderText="Delete Record">
<ControlStyleCssClass="btn btn-info"></ControlStyle>
</asp:ButtonField>
Step 5:

Now add the code to the events:

Details
protectedvoid GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
     int index = Convert.ToInt32(e.CommandArgument);
     if (e.CommandName.Equals("detail"))
     {
          int ID = Convert.ToInt32(grdvCrudOperation.DataKeys[index].Value.ToString());
          IEnumerable<DataRow> query = from i in dt.AsEnumerable()  where i.Field<int>("ID").Equals(ID)
          select i;
          DataTable detailTable = query.CopyToDataTable<DataRow>();
          DetailsView1.DataSource = detailTable;
          DetailsView1.DataBind();
          System.Text.StringBuilder sb = new System.Text.StringBuilder();
          sb.Append(@"<script type='text/javascript'>");
          sb.Append("$('#detailModal').modal('show');");
          sb.Append(@"</script>");
          ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "DetailModalScript", sb.ToString(), false);
     }

}

 RowEditing

protectedvoid GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    int index = Convert.ToInt32(e.CommandArgument);
    if (e.CommandName.Equals("editRecord"))
    {
       GridViewRow gvrow = grdvCrudOperation.Rows[index];
       HfUpdateID.Value = HttpUtility.HtmlDecode(gvrow.Cells[3].Text).ToString();          txtNameUpdate.Text = HttpUtility.HtmlDecode(gvrow.Cells[4].Text);        txtEmailIDUpdate.Text = HttpUtility.HtmlDecode(gvrow.Cells[5].Text);
       txtAddressUpdate.Text = HttpUtility.HtmlDecode(gvrow.Cells[6].Text);
       txtContactUpdate.Text = HttpUtility.HtmlDecode(gvrow.Cells[7].Text);
       lblResult.Visible = false;
       System.Text.StringBuilder sb = new System.Text.StringBuilder();
       sb.Append(@"<script type='text/javascript'>");
       sb.Append("$('#editModal').modal('show');");
       sb.Append(@"</script>");        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditModalScript", sb.ToString(), false);  
   }
}

protectedvoid btnSave_Click(object sender, EventArgs e)
{
   string message = string.Empty;
   try    {

     SqlConnection connection = GlobalClass.OpenConnection(out message);
     if (connection != null && string.IsNullOrEmpty(message))
    {
         SqlCommand cmd = newSqlCommand("Proc_UpdateGridView", connection);
         cmd.CommandType = CommandType.StoredProcedure;
         cmd.Parameters.AddWithValue("@ID",HfUpdateID.Value);
         cmd.Parameters.AddWithValue("@Name", txtNameAdd.Text.Trim());
         cmd.Parameters.AddWithValue("@EmailID", txtEmailIDAdd.Text.Trim());
         cmd.Parameters.AddWithValue("@Address", txtAddressAdd.Text.Trim());
         cmd.Parameters.AddWithValue("@Contact", txtContactAdd.Text.Trim());
         int row = cmd.ExecuteNonQuery();
     }
   }
   catch (Exception ex)
   {
        message = ex.Message;
   }

   finally
   {
       GlobalClass.CloseConnection(out message);
   }    DataLoad();
   System.Text.StringBuilder sb = new System.Text.StringBuilder();
   sb.Append(@"<script type='text/javascript'>");
   sb.Append("alert('Records Updated Successfully');");
   sb.Append("$('#editModal').modal('hide');");
   sb.Append(@"</script>");
   ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "EditHideModalScript", sb.ToString(), false);

}

 RowDeleting

protectedvoid GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{

    int index = Convert.ToInt32(e.CommandArgument);
    if (e.CommandName.Equals("deleteRecord"))
    {
        string code = grdvCrudOperation.DataKeys[index].Value.ToString();
        HfDeleteID.Value = code;
        System.Text.StringBuilder sb = new System.Text.StringBuilder();
        sb.Append(@"<script type='text/javascript'>");
        sb.Append("$('#deleteModal').modal('show');");
        sb.Append(@"</script>");
        ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "DeleteModalScript", sb.ToString(), false);
    }
}
protectedvoid btnDelete_Click(object sender, EventArgs e)
{
   string message = string.Empty;
   try
   {

      SqlConnection connection = GlobalClass.OpenConnection(out message);
      if (connection != null && string.IsNullOrEmpty(message))
      {
          SqlCommand cmd = newSqlCommand("Proc_DeleteGridView", connection);
          cmd.CommandType = CommandType.StoredProcedure;
          cmd.Parameters.AddWithValue("@ID", HfDeleteID.Value);
          int row = cmd.ExecuteNonQuery();
      }
   }
   catch (Exception ex)
   {
       message = ex.Message;
   }
   finally
   {
       GlobalClass.CloseConnection(out message);   }
   DataLoad();
   System.Text.StringBuilder sb = new System.Text.StringBuilder();
   sb.Append(@"<script type='text/javascript'>");
   sb.Append("alert('Record deleted Successfully');");
   sb.Append("$('#deleteModal').modal('hide');");
   sb.Append(@"</script>");
   ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "delHideModalScript", sb.ToString(), false);

}

 RecordInserted

protectedvoid btnAdd_Click(object sender, EventArgs e) //Open Model popup
{
   System.Text.StringBuilder sb = new System.Text.StringBuilder();
   sb.Append(@"<script type='text/javascript'>");
   sb.Append("$('#addModal').modal('show');");
   sb.Append(@"</script>");
   ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AddShowModalScript", sb.ToString(), false);  

}
protectedvoid btnAddRecord_Click(object sender, EventArgs e)
{    string message = string.Empty;
   try
   {
      SqlConnection connection = GlobalClass.OpenConnection(out message);
      if (connection != null && string.IsNullOrEmpty(message))
      {          SqlCommand cmd = newSqlCommand("Proc_SaveGridView", connection);
         cmd.CommandType = CommandType.StoredProcedure;
         cmd.Parameters.AddWithValue("@Name", txtNameAdd.Text.Trim());
         cmd.Parameters.AddWithValue("@EmailID", txtEmailIDAdd.Text.Trim());
         cmd.Parameters.AddWithValue("@Address", txtAddressAdd.Text.Trim());
         cmd.Parameters.AddWithValue("@Contact", txtContactAdd.Text.Trim());
         int row = cmd.ExecuteNonQuery();
      }

   }
   catch (Exception ex)
   {
        message = ex.Message;
   }
    finally
    {
        GlobalClass.CloseConnection(out message);
    }
    DataLoad();
    System.Text.StringBuilder sb = new System.Text.StringBuilder();
    sb.Append(@"<script type='text/javascript'>");
    sb.Append("alert('Record Added Successfully');");
    sb.Append("$('#addModal').modal('hide');");
    sb.Append(@"</script>");
    ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AddHideModalScript", sb.ToString(), false);

}
 GridView.aspx
<%@PageLanguage="C#" AutoEventWireup="true"CodeBehind="GridView.aspx.cs"Inherits="GridViewCRUDBootstrapExample.Default"%>
<!DOCTYPEhtml> <htmlxmlns="http://www.w3.org/1999/xhtml">
<headrunat="server">
    <title></title>
    <linkhref="Styles/bootstrap.css" rel="stylesheet"/>
    <scriptsrc="Scripts/jquery-1.8.2.js"></script>     <scriptsrc="Scripts/bootstrap.js"></script>
</head>
<body>
    <formid="form1"runat="server">
        <divstyle="width: 90%; margin-right: 5%; margin-left: 5%; text-align: center">
            <asp:ScriptManagerrunat="server"ID="ScriptManager1"/>             <h1>Grid View System</h1>
            <asp:UpdatePanelID="upCrudGrid"runat="server">
                <ContentTemplate>                     <asp:GridViewID="grdvCrudOperation"runat="server"Width="940px"HorizontalAlign="Center"
                        OnRowCommand="GridView1_RowCommand"AutoGenerateColumns="false"AllowPaging="true"
                        DataKeyNames="ID"CssClass="table table-hover table-striped">
                        <Columns>
                            <asp:ButtonField CommandName="detail"ControlStyle-CssClass="btn btn-info"ButtonType="Button"Text="Detail"HeaderText="Detailed View">
                                <ControlStyleCssClass="btn btn-info"></ControlStyle>                             </asp:ButtonField>
                            <asp:ButtonField CommandName="editRecord"ControlStyle-CssClass="btn btn-info"ButtonType="Button"Text="Edit"HeaderText="Edit Record">                                 <ControlStyleCssClass="btn btn-info"></ControlStyle>
                            </asp:ButtonField>
                            <asp:ButtonField CommandName="deleteRecord"ControlStyle-CssClass="btn btn-info"ButtonType="Button"Text="Delete"HeaderText="Delete Record">                                 <ControlStyleCssClass="btn btn-info"></ControlStyle>
                            </asp:ButtonField>
                            <asp:BoundField DataField="ID"HeaderText="ID"/>
                            <asp:BoundField DataField="Name"HeaderText="Name"/>
                            <asp:BoundField DataField="EmailID"HeaderText="EmailID"/>
                            <asp:BoundField DataField="Address"HeaderText="Address"/>
                            <asp:BoundField DataField="Contact"HeaderText="Contact NO"/>
                        </Columns>                     </asp:GridView>
                    <asp:ButtonID="btnAdd"runat="server"Text="Add New Record"CssClass="btn btn-info"OnClick="btnAdd_Click"/>                 </ContentTemplate>
                <Triggers>
                </Triggers>
            </asp:UpdatePanel>

            <divid="detailModal" class="modal hide fade"tabindex="-1"role="dialog"aria-labelledby="myModalLabel"aria-hidden="true">
                <divclass="modal-header">
                    <buttontype="button" class="close"data-dismiss="modal"aria-hidden="true">×</button>
                    <h3id="myModalLabel">Details</h3>
                </div>
                <divclass="modal-body">
                    <asp:UpdatePanelID="UpdatePanel2"runat="server">
                        <ContentTemplate>
                            <asp:DetailsView ID="DetailsView1"runat="server"CssClass="table table-bordered table-hover"BackColor="White"ForeColor="Black"FieldHeaderStyle-Wrap="false"FieldHeaderStyle-Font-Bold="true"FieldHeaderStyle-BackColor="LavenderBlush"FieldHeaderStyle-ForeColor="Black"BorderStyle="Groove"AutoGenerateRows="False">
                              <Fields>
                                    <asp:BoundField DataField="Name"HeaderText="Name"/>
                                    <asp:BoundField DataField="EmailID"HeaderText="EmailID"/>
                                    <asp:BoundField DataField="Address"HeaderText="Address"/>
                                    <asp:BoundField DataField="Contact"HeaderText="Contact NO"/>
                                </Fields>
                            </asp:DetailsView>
                        </ContentTemplate>
                        <Triggers>
                            <asp:AsyncPostBackTrigger ControlID="grdvCrudOperation"EventName="RowCommand"/>
                            <asp:AsyncPostBackTrigger ControlID="btnAdd"EventName="Click"/>
                        </Triggers>
                    </asp:UpdatePanel>
                    <divclass="modal-footer">
                        <buttonclass="btn btn-info"data-dismiss="modal"aria-hidden="true">Close</button>
                    </div>                 </div>
            </div>
            <divid="editModal" class="modal hide fade"tabindex="-1"role="dialog"aria-labelledby="editModalLabel"aria-hidden="true">
                <divclass="modal-header">
                    <buttontype="button" class="close"data-dismiss="modal"aria-hidden="true">×</button>
                    <h3id="editModalLabel">Edit Record</h3>
                </div>                 <asp:UpdatePanelID="upEdit"runat="server">
                    <ContentTemplate>                         <divclass="modal-body">
                            <asp:HiddenField ID="HfUpdateID"runat="server"/>
                            <tableclass="table">
                                <tr>
                                    <td>Name : </td>
                                    <td>
                                        <asp:TextBox ID="txtNameUpdate"runat="server"></asp:TextBox></td>
                                    <td>
                                </tr>
                                <tr>    <td>EmailID</td>
                                    <td>
                                        <asp:TextBox ID="txtEmailIDUpdate"runat="server"></asp:TextBox></td>
                                </tr>
                                <tr>
                                    <td>Address</td>
                                    <td>
                                        <asp:TextBox ID="txtAddressUpdate"runat="server"></asp:TextBox></td>
                                </tr>
                                <tr>
                                    <td>Contact No</td>
                                    <td>
                                        <asp:TextBox ID="txtContactUpdate"runat="server"></asp:TextBox></td>
                                </tr>
                            </table>
                        </div>
                        <divclass="modal-footer">
                            <asp:Label ID="lblResult"Visible="false"runat="server"></asp:Label>
                            <asp:Button ID="btnSave"runat="server"Text="Update"CssClass="btn btn-info"OnClick="btnSave_Click"/>
                            <buttonclass="btn btn-info"data-dismiss="modal"aria-hidden="true">Close</button>
                        </div>
                    </ContentTemplate>
                    <Triggers>
                        <asp:AsyncPostBackTrigger ControlID="grdvCrudOperation"EventName="RowCommand"/>
                        <asp:AsyncPostBackTrigger ControlID="btnSave"EventName="Click"/>
                    </Triggers>
                </asp:UpdatePanel>
            </div>

            <divid="addModal" class="modal hide fade"tabindex="-1"role="dialog"aria-labelledby="addModalLabel"aria-hidden="true">
                <divclass="modal-header">
                    <buttontype="button" class="close"data-dismiss="modal"aria-hidden="true">×</button>
                    <h3id="addModalLabel">Add New Record</h3>
                </div>
                <asp:UpdatePanelID="upAdd"runat="server">
                    <ContentTemplate>
                        <divclass="modal-body">
                            <tableclass="table table-bordered table-hover">
                                <tr>    <td>Name : </td>
                                    <td>
                                        <asp:TextBox ID="txtNameAdd"runat="server"></asp:TextBox></td>
                                </tr>
                                <tr>
                                    <td>EmailID :</td>
                                    <td>                                         <asp:TextBox ID="txtEmailIDAdd"runat="server"></asp:TextBox></td>
                                </tr>
                                <tr>
                                    <td>Address:</td>
                                    <td>
                                        <asp:TextBox ID="txtAddressAdd"runat="server"></asp:TextBox></td>
                                </tr>
                                <tr>
                                    <td>Contact No:</td>
                                    <td>
                                        <asp:TextBox ID="txtContactAdd"runat="server"></asp:TextBox></td>
                                </tr>
                            </table>
                        </div>
                        <divclass="modal-footer">
                            <asp:Button ID="btnAddRecord"runat="server"Text="Add"CssClass="btn btn-info"OnClick="btnAddRecord_Click"/>
                            <buttonclass="btn btn-info"data-dismiss="modal"aria-hidden="true">Close</button>
                        </div>
                    </ContentTemplate>
                    <Triggers>
                        <asp:AsyncPostBackTrigger ControlID="btnAddRecord"EventName="Click"/>
                    </Triggers>
                </asp:UpdatePanel>
            </div>
            <divid="deleteModal" class="modal hide fade"tabindex="-1"role="dialog"aria-labelledby="delModalLabel"aria-hidden="true">
                <divclass="modal-header">
                    <buttontype="button" class="close"data-dismiss="modal"aria-hidden="true">×</button>
                    <h3id="delModalLabel">Delete Record</h3>
                </div>                 <asp:UpdatePanelID="upDel"runat="server">
                    <ContentTemplate>
                        <divclass="modal-body">
                            Are you sure you want to delete the record?
                            <asp:HiddenField ID="HfDeleteID"runat="server"/>
                        </div>
                        <divclass="modal-footer">
                            <asp:Button ID="btnDelete"runat="server"Text="Delete"CssClass="btn btn-info"OnClick="btnDelete_Click"/>
                            <buttonclass="btn btn-info"data-dismiss="modal"aria-hidden="true">Cancel</button>
                        </div>
                    </ContentTemplate>
                    <Triggers>                         <asp:AsyncPostBackTrigger ControlID="btnDelete"EventName="Click"/>
                    </Triggers>
                </asp:UpdatePanel>
            </div>
        </div>
    </form>
</body>
</html>
 

  Use this BootStrap File :-  

 
<linkhref="Styles/bootstrap.css"rel="stylesheet"/> 
<scriptsrc="Scripts/jquery-1.8.2.js"></script> 
<scriptsrc="Scripts/bootstrap.js"></script>

 Download and add the above three files into your projects because it’s mandatory for using the bootstrap libraries and methods.

When you run the project, it will show you all the values from the database. 

Output

Editable Grid View System using BootStrap in ASP.Net 

When you click the “Add New Record” button:

Editable Grid View System using BootStrap in ASP.Net

 Fill the form with your appropriate values and click on “Add” button. Clicking on “Add” button will insert the record.

Editable Grid View System using BootStrap in ASP.Net

  When you click the “Detail” button: 

Editable Grid View System using BootStrap in ASP.Net

  When you click the “Edit” button: 

Editable Grid View System using BootStrap in ASP.Net

Fill the form with your appropriate values and click on “Update” button. Clicking on “Update” button will Updated the record.  

Editable Grid View System using BootStrap in ASP.Net 

When you click the delete button:

I have deleted the “Dev Karan Patel” record. 

Editable Grid View System using BootStrap in ASP.Net 

If you click “Delete” button then record deleted 

Editable Grid View System using BootStrap in ASP.Net


Updated 10-Sep-2020
I am a content writter !

Leave Comment

Comments

Liked By